require('dotenv').config();
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const cron = require('node-cron');
const path = require('path');

// 导入路由
const sourceRoutes = require('./routes/sources');
const personnelRoutes = require('./routes/personnel');
const changelogRoutes = require('./routes/changelog');
const authRoutes = require('./routes/auth');

// 导入服务
const monitorService = require('./services/monitorService');

const app = express();
const PORT = process.env.PORT || 5000;
const DEV_MODE = process.env.NODE_ENV === 'development';

// 中间件
app.use(cors());
app.use(express.json());

// 连接数据库
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/intelligence-system')
  .then(() => console.log('MongoDB连接成功'))
  .catch(err => {
    console.error('MongoDB连接失败:', err);
    if (!DEV_MODE) {
      // 在生产环境，如果无法连接数据库则退出
      process.exit(1);
    } else {
      console.log('开发模式: 继续启动服务器，但数据库功能将不可用');
    }
  });

// 设置路由
app.use('/api/sources', sourceRoutes);
app.use('/api/personnel', personnelRoutes);
app.use('/api/changelog', changelogRoutes);
app.use('/api/auth', authRoutes);

// 在生产环境提供静态资源
if (process.env.NODE_ENV === 'production') {
  app.use(express.static(path.join(__dirname, '../../client/build')));
  app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, '../../client/build', 'index.html'));
  });
}

// 定时任务 - 每天凌晨2点执行监测
if (!DEV_MODE || process.env.ENABLE_CRON === 'true') {
  cron.schedule('0 2 * * *', async () => {
    console.log('执行定时监测任务...');
    try {
      await monitorService.monitorAllSources();
      console.log('定时监测任务完成');
    } catch (error) {
      console.error('定时监测任务失败:', error);
    }
  });
} else {
  console.log('开发模式: 定时任务已禁用');
}

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
}); 